<?php
/**
 * Created by PhpStorm.
 * User: tandunzhao
 * Date: 2018/5/30
 * Time: 下午1:47
 */

namespace App\Modules\Auth\Services;


use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use App\Jobs\CaptchaRecordSave;
use Redis;

class SmsService
{
    protected $accessKeyId;
    protected $accessSecret;
    protected $signName;
    protected $TemplateCode;
    public function __construct($templateCode='',$accessKeyId='',$accessSecret='',$signName='')
    {
        $this->accessKeyId = $accessKeyId?$accessKeyId:env('ALICLOUD_SMS_accessKeyId');
        $this->accessSecret = $accessSecret?$accessSecret:env('ALICLOUD_SMS_accessSecret');
        $this->signName = $signName?$signName:env('ALICLOUD_SMS_signName');
        $this->TemplateCode = $templateCode;
        AlibabaCloud::accessKeyClient($this->accessKeyId,  $this->accessSecret)
            ->regionId('cn-hangzhou')
            ->asDefaultClient();
    }

    public function sendSms($phone) {

        try {
            $code = self::getRandomCode(5);
            $result = AlibabaCloud::rpc()
                ->product('Dysmsapi')
                ->version('2017-05-25')
                ->action('SendSms')
                ->method('POST')
                ->host('dysmsapi.aliyuncs.com')
                ->options([
                    'query' => [
                        'RegionId' => "cn-hangzhou",
                        'PhoneNumbers' => $phone,
                        'SignName' => env('ALICLOUD_SMS_signName'),
                        'TemplateCode' => $this->TemplateCode,
                        'TemplateParam' => "{\"code\":\"$code\"}",
                    ],
                ])
                ->request();
            //print_r($result->toArray());
            $res = $result->toArray();
            $job = (new CaptchaRecordSave(['phone'=>$phone,'code'=>$code]))->onConnection('redis');
            dispatch($job);
            if(isset($res['Message'])&&$res['Message']=='OK') {
                Redis::setex('MSG_SENT_DONE:'.$phone,60,1);
                Redis::setex('MSG_SENT_CODE:'.$phone,300,$code);
                return true;
            }
            \Log::error('send_message_failed:'.json_encode($res));
        } catch (ClientException $e) {
           \Log::error('SEND_MESSAGE_ERROR:Client:'.$e->getErrorMessage());
           return false;
        } catch (ServerException $e) {
            \Log::error('SEND_MESSAGE_ERROR:Server:'.$e->getErrorMessage());
            return false;
        }

        return false;
    }

    protected static function getRandomCode($length=5) {
        $randStr = str_shuffle('1234567890');
        $rand = substr($randStr,0,$length);
        return $rand;
    }

    public static function checkPhone($phone) {

        return preg_match('/^1[3456789]\d{9}$/',$phone);

    }
}